<template>
  <a-upload
    v-model:file-list="fileList"
    name="file"
    :multiple="false"
    :action="up_load_url"
    :headers="headers.data.headers"
    @change="handleChange"
    :showUploadList="false"
    @preview="handlePreview"
    :remove="removeHandler"
    :beforeUpload="beforUploadHandler"
    v-bind="props.attrs"
  >
    <slot v-if="fileList.length < props.max">
      <a-button type="primary" :loading="loading" v-if="!ui">
        <upload-outlined></upload-outlined>
      </a-button>

      <component v-else :is="ui" :loading="loading" />
    </slot>
  </a-upload>
  <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
    <img alt="example" style="width: 100%" :src="previewImage" />
  </a-modal>
</template>

<script>
import { ref, reactive, defineComponent, computed } from 'vue'
import { message } from 'ant-design-vue'
import { getUserToken } from '@Config/server/localStorage'
import { UploadOutlined } from '@ant-design/icons-vue'
import { URL_PRIX, Messages } from '@Config/config'
import * as Ant from 'ant-design-vue'

export default defineComponent({
  components: {
    UploadOutlined,
    'a-button': Ant.Button,
    'a-upload': Ant.Upload,
    'a-modal': Ant.Modal,
  },
  props: {
    upload_url: {
      type: String,
      default: () => {
        return ''
      },
    },
    attrs: {
      type: Object,
      default: () => {
        return {}
      },
    },
    max: {
      type: Number,
      default: 1,
    },
    value: {
      type: Array,
      default: () => {
        return []
      },
    },
    file: {
      type: Boolean,
      default: () => {
        return false
      },
    },
    //  validator={{
    //           naturalWidth: {
    //             range: [100, 200],
    //             msg: '请输入正确的宽度[100px,200px]',
    //             type: 'range',
    //           },
    //           naturalHeight: {
    //             range: [100, 200],
    //             msg: '请输入正确的高度[100px,200px]',
    //             type: 'range',
    //           },
    //           size: {
    //             range: [0, 200],
    //             msg: '素材容量应该在[1, 20]Kb间',
    //             type: 'range',
    //           },
    //           type: {
    //             type: 'oneof',
    //             msg: 'aaaaaaa',
    //             oneof: ['image/gif'],
    //           },
    //         }}
    validator: {
      type: Object,
      default: () => {
        return
      },
    },
    ui: {
      type: Object,
      default: () => {
        return null
      },
    },
  },

  emits: ['complete', 'remove'],
  setup(props, context) {
    let ui = computed(() => props.ui)
    let validator = computed(() => {
      return {
        size: {
          range: [0, 500 * 1024],
          msg: '素材容量不能超过500Kb',
          type: 'range',
        },
        ...props.validator,
      }
    })

    const getBase64 = (file) => {
      return new Promise((resolve, reject) => {
        const reader = new FileReader()
        reader.readAsDataURL(file)

        reader.onload = () => resolve(reader.result)

        reader.onerror = (error) => reject(error)
      })
    }
    const previewVisible = ref(false)

    const previewImage = ref('')
    const handlePreview = async (file) => {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj)
      }

      previewImage.value = file.url || file.preview
      previewVisible.value = true
    }

    let values = computed(() => {
      return props.value
    })

    //上传列表
    let fileList = ref(values.value || [])
    let loading = ref(false)
    //上传网络状态
    const handleChange = ({ file, fileList, event }) => {
      loading.value = true

      if (file.status == 'uploading') return

      if (file.status == 'error') {
        Messages.add(message.error('上传发生错误'))
      }
      if (file.status == 'done') {
        if (file.response.code != 0) {
          Messages.add(message.error('上传失败' + file.response.msg))
        } else {
          //上传成功后，把服务端返回的数据，通过事件返回给调用者
          context.emit('complete', file.response)
        }
      }
      loading.value = false
    }
    let headers = reactive({
      data: { headers: { usertokenxm: getUserToken() } },
    })
    let up_load_url = URL_PRIX + props.upload_url
    const handleCancel = () => {
      previewVisible.value = false
    }

    const removeHandler = (file) => {
      context.emit('complete', { code: 0, data: null })
      context.emit('remove', { code: 0, data: file })

      // console.log(fileList.value[0].response)
    }

    const realFiles = computed(() => {
      return fileList.value
        .filter((x) => {
          return x.status == 'done'
        })
        .map((x) => {
          return x.status
        })
    })

    let beforUploadHandler = (file, fileList) => {
      //如果是上传文件，则不检测
      if (props.file) {
        return Promise.resolve()
      }
      return new Promise((resolve, reject) => {
        const reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = () => {
          //获取真实元素
          let image = document.createElement('img')
          image.src = reader.result
          image.style.width = '0px'
          image.style.height = '0px'
          document.body.append(image)
          image.onload = (e) => {
            image.size = file.size
            image.type = file.type

            let _validator_status = true
            for (var prop in validator.value) {
              if (validator.value[prop].type == 'range') {
                if (
                  image[prop] >= validator.value[prop].range[0] &&
                  image[prop] <= validator.value[prop].range[1]
                ) {
                  // console.log('正确')
                } else {
                  Messages.add(message.error(validator.value[prop].msg))
                  _validator_status = false
                  break
                }
              } else if (validator.value[prop].type == 'oneof') {
                let _index = validator.value[prop].oneof.indexOf(
                  image.type.toLocaleLowerCase()
                )
                if (_index < 0) {
                  _validator_status = false
                  Messages.add(message.error(validator.value[prop].msg))

                  break
                }
              }
            }
            if (!_validator_status) {
              reject()
            } else {
              resolve()
            }
            context.emit('complete', { code: 0, data: null })

            document.body.removeChild(image)
            // console.log(image, image.naturalWidth, image.naturalHeight)
          }
        }
      })
    }

    // const clickHandler = () => {
    //   let _key = { notify: uniqueId('notification') }
    //   notification.open({
    //     key: _key.notify,
    //     duration: 5,
    //     message: '导入数据提示',
    //     description: h('span', { style: { color: '#ff0000' } }, importMaxTips),
    //   })
    //   Messages.add(_key)
    // }
    return {
      removeHandler,
      realFiles,
      handleChange,
      up_load_url,
      headers,
      loading,
      props,
      handlePreview,
      previewImage,
      previewVisible,
      handleCancel,
      fileList,
      beforUploadHandler,
      validator,
      ui,
      // clickHandler,
    }
  },
})
</script>
